import OSS from 'ali-oss'
import { getOssTemporaryToken } from '@api/api'
let stsInfo = {
  accessKeyId: null,  //账户标识
  accessKeySecret: null,  //账户秘钥
  securityToken: null,
  dir: null,
  requestId: null,
  host: null
}
export function put (name, File, bucket, dir) {
  try {
    return new Promise((resolve, reject) => {
      if (!stsInfo.message) {
        return getOssTemporaryToken().then(result => {
          stsInfo = result.result
          resolve(stsInfo)
        })
      } else {
        resolve(stsInfo)
      }
    }).then(stsInfo => {
      console.log(stsInfo)
      const client = new OSS({
        region: 'oss-cn-hangzhou',  //'创建bucket的地区',
        accessKeyId: stsInfo.accessKeyId,
        accessKeySecret:stsInfo.accessKeySecret,
        bucket: bucket,  //bucket的名字
        stsToken: stsInfo.securityToken,
      })
      return client.put( dir + name, File)
    })
  } catch (e) {
    console.log(e)
  }
}



export function putOssInfo (fileName, file) {
  let bucket = process.env.VUE_APP_OSS_BUCKET;
  try {
    return new Promise((resolve, reject) => {
      if (!stsInfo.message) {
        return getOssTemporaryToken().then(result => {
          stsInfo = result.result
          resolve(stsInfo)
        })
      } else {
        resolve(stsInfo)
      }
    }).then(stsInfo => {
      const client = new OSS({
        region: 'oss-cn-hangzhou',  //填写Bucket所在地域
        accessKeyId: stsInfo.accessKeyId,  //从STS服务获取的临时访问密钥
        accessKeySecret:stsInfo.accessKeySecret,
        bucket: bucket, //填写Bucket名称。
        stsToken: stsInfo.securityToken,  //从STS服务获取的安全令牌（SecurityToken）。
      })

      return client.put( '', file)

    })
  } catch (e) {
    console.log(e)
  }
}

